package cn.hairui.blog.controller.manage;

import cn.hairui.blog.constant.PubConstant;
import cn.hairui.blog.model.Book;
import cn.hairui.blog.model.User;
import cn.hairui.blog.service.BookService;
import cn.hairui.blog.util.CommUtil;
import cn.hairui.blog.util.DateUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * <p>
 * <h2>请添加说明
 * </h2>
 * <ol>请添加详细说明
 * </ol>
 *
 * <h2>修改历史
 * </h2>
 * <ol>如有修改，请添加修改历史
 * </ol>
 *
 * </p>
 *
 * @author laoganbu
 * @version V1.0
 * @date 2019/8/9 16:36
 */
@Controller
@RequestMapping(value = "/manage")
public class BookManageController {

    @Autowired
    private BookService bookService;

    @Value("${upload_path}")
    private String uploadPath;

    @Value("${virtual_upload_path}")
    private String virtualUploadPath;

    //列表页面
    @RequestMapping(value = "page/book/bookList")
    public String bookList() {
        return "manage/page/book/bookList";
    }

    //新增页面
    @RequestMapping(value = "page/book/bookAdd")
    public String bookAdd() {
        return "manage/page/book/bookAdd";
    }

    //修改页面
    @RequestMapping(value = "page/book/bookUpdate")
    public String bookUpdate(HttpServletRequest request, Model model) {
        int id = Integer.parseInt(request.getParameter("id"));
        Book book = bookService.find(id);
        model.addAttribute("book", book);
        return "manage/page/book/bookUpdate";
    }

    //列表数据
    @RequestMapping(value = "page/book/list")
    @ResponseBody
    public String list(HttpServletRequest request) {
        Map map = new HashMap<Object, Object>();
        int pageSize = 5;//默认每页显示5条记录
        int pageNum = 1;
        try {
            pageNum = Integer.parseInt(request.getParameter("page"));
            pageSize = Integer.parseInt(request.getParameter("limit"));
        } catch (Exception e) {
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Map> bookList = bookService.listMgr();

        PageInfo<Map> pageInfo = new PageInfo<Map>(bookList);
        map.put("data", bookList);
        map.put("code", 0);
        map.put("count", pageInfo.getTotal());
        return JSONUtils.toJSONString(map);
    }


    //新增数据
    @RequestMapping(value = "page/book/add")
    @ResponseBody
    public String add(HttpServletRequest request, String bookName, String author, String publishDate) {

        Book book = new Book();
        book.setBookName(bookName);
        book.setAuthor(author);
        book.setPublishDate(publishDate);

        Map map = new HashMap<Object, Object>();
        //补充添加时间
        book.setAddDate(DateUtil.getCurrentDate());
        List<Book> books = bookService.findByBookName(book.getBookName());
        if (books.size() >= 1) {
            map.put(PubConstant.flag, "exsit");
        } else {
            String fileName = "";
            File targetPath = new File(uploadPath + PubConstant.BOOK_DIR);
            if (!targetPath.exists()) {
                targetPath.mkdirs();
            }

            //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            //检查form中是否有enctype="multipart/form-data"
            if (multipartResolver.isMultipart(request)) {
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                //获取multiRequest 中所有的文件名
                Iterator iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    //一次遍历所有文件
                    MultipartFile file = multiRequest.getFile(iter.next().toString());
                    if (file != null) {
                        fileName = file.getOriginalFilename();
                        String suffixName = fileName.substring(fileName.lastIndexOf("."));
                        //重新生成文件名
                        fileName = CommUtil.getUUIDUpperCase() + suffixName;

                        String path = uploadPath + PubConstant.BOOK_DIR + fileName;
                        //上传
                        try {
                            file.transferTo(new File(path));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            book.setLocalPath(fileName);
            int serno = bookService.add(book);
            Logger.getLogger(this.getClass().getName()).info("新增书籍编号：" + serno);
            map.put(PubConstant.flag, PubConstant.success);
        }
        return JSONUtils.toJSONString(map);
    }


    //删除数据
    @RequestMapping(value = "page/book/delete", method = RequestMethod.POST)
    @ResponseBody
    public String delete(@Param(value = "id") int id, HttpServletRequest request) {
        Map map = new HashMap();
        //判断权限
        User userinfo = (User) request.getSession().getAttribute(PubConstant.GLOBAL_SESSION_NAME);
        if (userinfo == null || !PubConstant.YES_NO_Y.equals(userinfo.getAdminflag())) {
            //普通用户或者游客 无权限删除文章
            map.put(PubConstant.flag, PubConstant.permissions);
        } else {
            //管理员

            //删除文件
            try {
                Book bean = bookService.find(id);
                String fileName = bean.getLocalPath();
                String filePath = virtualUploadPath + PubConstant.BOOK_DIR + fileName;
                File file = new File(filePath);
                if (file.exists()) {
                    file.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            bookService.delete(id);
            map.put(PubConstant.flag, PubConstant.success);
        }
        return JSONUtils.toJSONString(map);
    }

    //修改页面
    @RequestMapping(value = "page/book/bookCover")
    public String bookCover(HttpServletRequest request, Model model) {
        int id = Integer.parseInt(request.getParameter("id"));
        Book book = bookService.find(id);
        model.addAttribute("book", book);
        return "manage/page/book/bookCover";
    }


    @RequestMapping(value = "page/book/cover")
    @ResponseBody
    public String cover(HttpServletRequest request, Integer id) {
        Map map = new HashMap<Object, Object>();
        String fileName = "";
        File targetPath = new File(uploadPath + PubConstant.BOOK_DIR + PubConstant.COVERS_DIR);
        if (!targetPath.exists()) {
            targetPath.mkdirs();
        }

        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    fileName = file.getOriginalFilename();
                    String suffixName = fileName.substring(fileName.lastIndexOf("."));
                    //重新生成文件名
                    fileName = CommUtil.getUUIDUpperCase() + suffixName;

                    String path = uploadPath + PubConstant.BOOK_DIR + PubConstant.COVERS_DIR + fileName;
                    //上传
                    try {
                        file.transferTo(new File(path));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        bookService.updateCover(id, fileName);
        map.put(PubConstant.flag, PubConstant.success);
        return JSONUtils.toJSONString(map);
    }
}
